package com.home.common.handler;

import com.home.base.core.framework.enums.ResultCodeEnum;
import com.home.base.core.framework.msg.ServerResponse;
import com.home.common.handler.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

/**
 * Description: 全局异常处理
 * Created by 王大宸 on 2020-09-23 0:37
 * Created with IntelliJ IDEA.
 */
@RestControllerAdvice(basePackages = {"com.home"})
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 未捕获到的未知异常
     */
    @ExceptionHandler(Exception.class)
    public ServerResponse<String> otherExceptionHandler(HttpServletResponse response, Exception ex) {
        logger.error(ex.getMessage(), ex);
        response.setStatus(HttpStatus.OK.value());
        return ServerResponse.errStatusMsg(ResultCodeEnum.EXCEPTION.getStatus(), ResultCodeEnum.EXCEPTION.getMessage());
    }

    /**
     * 统一异常处理,自定义抛出异常
     */
    @ExceptionHandler(BizException.class)
    public ServerResponse<String> bizExceptionHandler(HttpServletResponse response, BizException ex) {
        logger.error(ex.getMessage(), ex);
        response.setStatus(HttpStatus.OK.value());
        return ServerResponse.errStatusMsg(ex.getStatus(), ex.getMessage());
    }

}
